<template>
  <el-container class="order-confirmation-container">
    <el-main>
      <el-card class="confirmation-card">
        <div v-if="loading" class="loading-spinner">
          <el-progress :percentage="50" :indeterminate="true" />
          <p>正在加载订单信息...</p>
        </div>
        <div v-else-if="error" class="error-message">
          <el-result icon="error" title="订单信息加载失败" :sub-title="error">
            <template #extra>
              <el-button type="primary" @click="goToHome">返回首页</el-button>
              <el-button @click="retryLoadOrder">重试</el-button>
            </template>
          </el-result>
        </div>
        <div v-else-if="order" class="confirmation-content">
          <el-result icon="success" title="订单提交成功！" sub-title="感谢您的购买，我们会尽快为您处理订单。">
            <template #extra>
              <el-button type="primary" @click="goToOrderDetail(order.order_number)">查看订单详情</el-button>
              <el-button @click="goToProducts">继续购物</el-button>
            </template>
          </el-result>

          <el-descriptions title="订单概要" :column="1" border style="margin-top: 30px;">
            <el-descriptions-item label="订单号">{{ order.order_number }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">{{ order.status_display || order.status }}</el-descriptions-item>
            <el-descriptions-item label="订单总金额">
              <strong style="color: #ff4d4f;">¥{{ order.total_amount }}</strong>
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ order.payment_method_display || order.payment_method }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatDateTime(order.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="收货人">{{ order.shipping_address?.recipient_name }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ order.shipping_address?.phone_number }}</el-descriptions-item>
            <el-descriptions-item label="收货地址">
              {{ order.shipping_address?.province }}{{ order.shipping_address?.city }}{{ order.shipping_address?.district }} {{ order.shipping_address?.street_address }}
            </el-descriptions-item>
            <el-descriptions-item v-if="order.customer_remarks" label="订单备注">
              {{ order.customer_remarks }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-else>
          <el-empty description="未找到订单信息。"></el-empty>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import orderService from '../api/order.service';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();

const order = ref(null);
const loading = ref(true);
const error = ref(null);

const fetchOrderDetail = async () => {
  try {
    loading.value = true;
    error.value = null;
    const orderNumber = route.params.orderNumber;
    if (!orderNumber) {
      throw new Error('订单号不存在');
    }
    const response = await orderService.getOrder(orderNumber);
    if (!response || !response.data) {
      throw new Error('获取订单信息失败');
    }
    order.value = response.data;
  } catch (err) {
    console.error('获取订单详情失败:', err);
    error.value = err.message || '获取订单详情失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return 'N/A';
  try {
    return new Date(dateTimeString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (e) {
    console.warn('日期格式化失败:', e);
    return dateTimeString;
  }
};

const goToProducts = () => {
  router.push({ name: 'Products' });
};

const goToHome = () => {
  router.push({ name: 'Home' });
};

const retryLoadOrder = () => {
  if (route.params.orderNumber) {
    fetchOrderDetail();
  } else {
    router.push('/orders');
  }
};

const goToOrderDetail = (orderNumber) => {
  if (!orderNumber) {
    ElMessage.warning('订单号无效');
    return;
  }
  router.push(`/orders/${orderNumber}`);
};

watch(
  () => route.params.orderNumber,
  (newOrderNumber) => {
    if (newOrderNumber) {
      fetchOrderDetail();
    }
  },
  { immediate: true }
);

onBeforeUnmount(() => {
  order.value = null;
  loading.value = false;
  error.value = null;
});
</script>

<style scoped>
.order-confirmation-container {
  padding: 20px;
  background-color: #f5f5f5;
}

.confirmation-card {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.loading-spinner,
.error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}

.confirmation-content .el-result {
  padding-bottom: 0;
}

.el-descriptions {
  margin-top: 20px;
}
</style> 